<template>
  <div>
    <div class="time-selector">
      <div class="datetime">
        <input
          type="datetime-local"
          :name="mode + 'date'"
          class="date-time"
          v-model="createDatetime"
          @change="datetimeChange"
          :readonly="lock"
        />
      </div>
      <div>→</div>
      <select name="year" v-model="year" @change="dataChange" :disabled="lock">
        <option
          v-for="cycle in sixtyYearsCycle"
          v-bind:key="cycle.heavenStem.name + cycle.earthBranch.name"
          v-bind:value="cycle.heavenStem.name + cycle.earthBranch.name"
        >
          {{ cycle.heavenStem.name }}{{ cycle.earthBranch.name }}年
        </option>
      </select>
      <select
        name="month"
        v-model="month"
        @change="dataChange"
        :disabled="lock"
      >
        <option
          v-for="cycle in sixtyYearsCycle"
          v-bind:key="cycle.heavenStem.name + cycle.earthBranch.name"
          v-bind:value="cycle.heavenStem.name + cycle.earthBranch.name"
        >
          {{ cycle.heavenStem.name }}{{ cycle.earthBranch.name }}月
        </option>
      </select>
      <select name="monthBranch" v-model="monthBranch" style="display: none">
        <option value="">选择月令</option>
        <option
          v-for="branch in earthBranches"
          v-bind:key="branch.name"
          v-bind:value="branch.name"
        >
          {{ branch.name }}月
        </option>
      </select>
      <select name="date" v-model="date" @change="dataChange" :disabled="lock">
        <option
          v-for="cycle in sixtyYearsCycle"
          v-bind:key="cycle.heavenStem.name + cycle.earthBranch.name"
          v-bind:value="cycle.heavenStem.name + cycle.earthBranch.name"
        >
          {{ cycle.heavenStem.name }}{{ cycle.earthBranch.name }}日
        </option>
      </select>
      <select name="time" v-model="time" @change="dataChange" :disabled="lock">
        <option
          v-for="cycle in sixtyYearsCycle"
          v-bind:key="cycle.heavenStem.name + cycle.earthBranch.name"
          v-bind:value="cycle.heavenStem.name + cycle.earthBranch.name"
        >
          {{ cycle.heavenStem.name }}{{ cycle.earthBranch.name }}时
        </option>
      </select>
      <div>
        <!-- <button @click="save" :disabled="lock">💾 保存</button>
        <button @click="reset" :disabled="lock">🔄 重置</button> -->
        <button @click="save" :disabled="lock" :class="{'new': isNew}">
          <span v-if="!showSaveSuccess">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-baocun"></use>
            </svg>
            保存
          </span>
          <span v-else class="save-success">
            <svg class="icon icon-save-success" aria-hidden="true">
              <use xlink:href="#icon-chenggong"></use>
            </svg>
            成功
          </span>
        </button>
        <button @click="reset" :disabled="lock">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-reset"></use>
          </svg>
          重置
        </button>
      </div>
    </div>

    <div class="floor2">
      <div class="configs">
        <input
          type="checkbox"
          name="showIcon"
          id="showIcon"
          v-model="showIcon"
          @change="toggleShowIcon"
        /><label for="showIcon">辅助特效</label>
      </div>
      <div class="power" v-if="mode == 'hexagram'">
        <div></div>
        <span v-if="monthBranch" title="月令"
          ><svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-weather-color_moon-stars"></use>
          </svg>
          <b :style="getHighlightColor(monthBranch, 'month')">
            {{ monthBranch
            }}<template v-if="showIcon"
              ><svg class="icon" aria-hidden="true">
                <use :xlink:href="'#icon-' + getIcon(monthBranch)"></use>
              </svg> </template></b
          >（{{ powerSixMembers.month.sixMember }}）<sup>{{
            powerSixMembers.month.godEvil
          }}</sup></span
        ><span v-if="date" title="日建">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-046-sun"></use>
          </svg>
          <b :style="getHighlightColor(date, 'date')">
            {{ date ? date[1] : ""
            }}<template v-if="showIcon"
              ><svg class="icon" aria-hidden="true">
                <use
                  :xlink:href="'#icon-' + getIcon(date ? date[1] : '')"
                ></use>
              </svg> </template></b
          >（{{ powerSixMembers.date.sixMember }}）<sup>{{
            powerSixMembers.date.godEvil
          }}</sup></span
        ><span v-if="dead" title="空亡"
          ><svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-wuJ_id"></use>
          </svg>
          {{ dead }} ({{ powerSixMembers.dead[0].sixMember }}
          {{ powerSixMembers.dead[1].sixMember }}）
          <!-- <sup>{{powerSixMembers.dead[0].godEvil}} | {{powerSixMembers.dead[1].godEvil}}</sup> -->
        </span>
        <div>
          <select
            name="highlight"
            v-model="highlight"
            @change="highlightChange"
          >
            <option value="">高亮辅助</option>
            <!-- <option value="combine3f">三会</option> -->
            <option value="combine3">三合</option>
            <option value="combine6">六合</option>
            <option value="impact">六冲</option>
            <option value="combineHalf">半合</option>
            <option value="penalty">三刑</option>
            <option value="snare">六害</option>
            <option value="born">长生</option>
            <option value="shower">沐浴</option>
            <option value="adult">冠带</option>
            <option value="official">临官</option>
            <option value="king">帝旺</option>
            <option value="weak">衰</option>
            <option value="ill">病</option>
            <option value="dead">死</option>
            <option value="tomb">墓</option>
            <option value="end">绝</option>
            <option value="embryo">胎</option>
            <option value="germination">养</option>
          </select>
        </div>
      </div>

      <div class="plumagram-numbers" v-if="mode == 'plumagram'">
        <input
          type="number"
          placeholder="上卦数"
          v-model="plumNumbers[0]"
          @change="plumNumbersChange"
          @keyup="plumNumbersChange"
          :readonly="lock"
        />
        <input
          type="number"
          placeholder="下卦数"
          v-model="plumNumbers[1]"
          @change="plumNumbersChange"
          @keyup="plumNumbersChange"
          :readonly="lock"
        />
        <input
          type="number"
          placeholder="变卦数"
          v-model="plumNumbers[2]"
          @change="plumNumbersChange"
          @keyup="plumNumbersChange"
          :readonly="lock"
        />
      </div>
    </div>
  </div>
</template>

<script>
// import Lunargz from "../core/lunargz";
import { Lunar } from "lunar-javascript";
import core from "../core/core";
import * as consts from "../core/consts";
import { EventBus } from "../core/event-bus";
import showMessage from "./messageBox";
export default {
  data() {
    return {
      createDatetime: this.formatDate(new Date()),
      year: "",
      month: "",
      date: "",
      time: "",
      monthBranch: "",
      sixtyYearsCycle: consts.getSortedSixtyYearsCycle(),
      earthBranches: consts.earthBranches,
      lock: false,
      plumNumbers: ["", "", ""],
      highlight: "",
      showIcon: true,
      showSaveSuccess: false,
      isNew: true
    };
  },
  props: ["mode", "powerSixMembers", "highlights"],
  methods: {
    datetimeChange: function (event) {
      // let lunargz = new Lunargz(new Date(this.createDatetime));

      // this.year = lunargz.gz[0];
      // this.month = lunargz.gz[1];
      // this.date = lunargz.gz[2];
      // this.time = lunargz.gz[3];
      
      const datetime = new Date(this.createDatetime);

      if (event && datetime.getHours() == 23) {
        showMessage("当前属于晚子时，是否翻至次日？", "customize", [
          {
            command: "next",
            text: "翻到次日",
          },
          { command: "cancel", text: "留在当日" },
        ]).then((x) => {
          if (x == "next") {
            datetime.setHours(datetime.getHours() + 1);
            const lunar = Lunar.fromDate(datetime);
            const bazi = lunar.getBaZi();
            this.year = bazi[0];
            this.month = bazi[1];
            this.date = bazi[2];
            this.time = bazi[3];

            this.dataChange();
          }
        });
      }

      const lunar = Lunar.fromDate(datetime);
      const bazi = lunar.getBaZi();
      this.year = bazi[0];
      this.month = bazi[1];
      this.date = bazi[2];
      this.time = bazi[3];

      this.dataChange();
    },

    dataChange: function () {
      if (this.month) this.monthBranch = this.month[1];
      else this.monthBranch = "";

      this.$emit("dataChange", {
        createDatetime: this.createDatetime,
        year: this.year,
        month: this.month,
        date: this.date,
        time: this.time,
        monthBranch: this.monthBranch,
        dead: this.dead,
      });
    },
    plumNumbersChange() {
      this.$emit("plumNumbersChange", this.plumNumbers);
    },
    save: function () {
      this.$emit("save");
      this.isNew = false;
    },
    reset: function () {
      showMessage(
        "确定重置并开启新卦例吗？\n重置：卦面上的内容不会发生改变，但是再次保存时将以新卦例保存，不再覆盖原卦例\n清空：卦面上的内容将被全部清空，重新开启一个新卦例",
        "customize",
        [
          { text: "重置", command: "reset" },
          { text: "清空", command: "clear" },
          { text: "取消", command: "cancel" },
        ]
      ).then((res) => {
        if (res == "clear") {
          this.createDatetime = this.formatDate(new Date());
          this.datetimeChange();
          this.plumNumbers = ["", "", ""];
        }
        if(res != "cancel")
          this.isNew = true;
        this.$emit("reset", res);
        
      });
    },
    _padStartZero: function (n, len) {
      return n.toString().padStart(len, "0");
    },
    formatDate: function (date) {
      return `${date.getFullYear()}-${this._padStartZero(
        date.getMonth() + 1,
        2
      )}-${this._padStartZero(date.getDate(), 2)}T${this._padStartZero(
        date.getHours(),
        2
      )}:${this._padStartZero(date.getMinutes(), 2)}`;
    },
    loadFromDb(data) {
      this.createDatetime = data.createDatetime;
      this.$nextTick(() => {
        this.year = data.year;
        this.month = data.month;
        this.date = data.date;
        this.time = data.time;
        this.dataChange();
      });
      if (data.plumNumbers) this.plumNumbers = data.plumNumbers;
    },
    highlightChange() {
      this.$emit("highlightChange", this.highlight);
    },
    getHighlightColor(monthOrDateBranchName, monthOrDate) {
      let style = {};

      if (monthOrDateBranchName) {
        const key = monthOrDateBranchName.split("").pop();
        if (this.highlights && this.highlights[monthOrDate]) {
          const light = core.getHighLight(
            this.highlights[monthOrDate],
            consts.earthBranches[key]
          );
          if (light)
            style = {
              color: light.color,
              fontWeight: "bold",
            };
        }
      }

      return style;
    },
    toggleShowIcon(event) {
      localStorage.setItem("hexagramShowIcon", event.target.checked);
      EventBus.$emit("hexagram-show-icon", event.target.checked);
    },
    getIcon(branch) {
      if (branch) return consts.earthBranches[branch].element.icon;
      return "";
    },
    saveSuccess(){
      this.showSaveSuccess = true;
      setTimeout(() => {
        this.showSaveSuccess = false;
      }, 3000);
    }
  },
  computed: {
    dead() {
      const dead = core.getDead(this.date);
      if (dead.length == 2) {
        return dead[0].earthBranch.name + dead[1].earthBranch.name;
      }
      return "";
    },
  },
  mounted() {
    EventBus.$on("lock", (x) => (this.lock = x));
    EventBus.$on(`${this.mode}s-load-diagram`, this.loadFromDb);
    const showIcon = localStorage.getItem("hexagramShowIcon");
    if (showIcon)
      this.showIcon = localStorage.getItem("hexagramShowIcon") == "true";

    //用于弥补在六爻和梅花页面切换时，checkbox的勾选状态不同步的问题
    EventBus.$on("hexagram-show-icon", (val) => {
      if (this.showIcon != val) this.showIcon = val;
    });

    EventBus.$on("load-diagram", ()=>{
      this.isNew = false;
    });
  },
};
</script>

<style lang="scss" scoped>
select {
  border: 0;
  outline: none;
  background: none;
}
.time-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2vmin 4vmin 4vmin 4vmin;

  .date-time {
    outline: none;
    border: 0;
    background: transparent;
  }
}
.floor2 {
  display: flex;
  justify-content: space-between;
  margin: 0 4vmin;
  margin-bottom: 2vmin;
  .configs {
    display: flex;
    align-items: center;
    justify-content: center;
    input[type="checkbox"] {
      width: 3vmin;
      height: 3vmin;
    }
  }
}
.power {
  display: flex;
  flex: 1;
  justify-content: space-evenly;
  align-items: center;

  span {
    margin: 0 5vmin;
    font-size: 3vmin;
    font-weight: bold;
    position: relative;
  }
  sup {
    position: absolute;
    left: 0;
    top: -3vmin;
    background: var(--rate-tip-color);
    white-space: nowrap;
    text-align: center;
    font-size: 2vmin;
    border-radius: 6px;
    padding: 0 1vmin;
    font-weight: normal;
  }
}

.plumagram-numbers {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-evenly;
  input {
    border: 0;
    border-bottom: solid 1px #ccc;
    background: transparent;
    outline: none;
  }
}
.save-success{
  opacity: 0;
  animation: fadeIn 3s ease-in-out forwards;
}

.new{
  position: relative;
  &::before{
    content: "NEW";
    display: block;
    position: absolute;
    left: -1.5vmin;
    top: -.8vmin;
    font-size: 1.5vmin;
    color: red;

  }
}



@keyframes fadeIn {
  0%{
    opacity: 0;
  }
  25%{
    opacity: 1;
  }
  75%{
    opacity: 1;
  }
  100%{
    opacity: 0;
  }
}
</style>
